<!-- 答题区域 -->
<template>
    <div class="answer-sheet">
        <div class="top">
            <el-button v-if="subjectsStore.curSubjectIndex === 0" type="primary" size="large" disabled>上一题</el-button>
            <el-button v-else type="primary" size="large" @click="upperStage">上一题</el-button>
            <h5>请勿离开本答题页面，否则将导致答案丢失！</h5>
            <div>
                <el-button v-if="subjectsStore.curSubjectIndex !== subjectsStore.subjetcLength - 1" type="primary"
                    size="large" @click="netxStage">下一题</el-button>
                <el-button v-else type="primary" size="large" @click="submitAnswer">提交答案</el-button>
                <el-button size="large" type="danger" @click="dialogVisible = true">确认最终答案</el-button>
            </div>
        </div>
        <!-- 因为是异步请求,所以需要用v-if来判断是否有数据 -->
        <div class="content" v-if="subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex] != null">
            <!-- 单选题 -->
            <el-form v-if="subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].questionType == 's'">
                <div class="subject-type"><span>单选题</span></div>
                <div class="subject">
                    <span>{{ subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].questionContent }}</span>
                </div>
                <el-radio-group v-model="answerBinds">
                    <el-radio
                        v-for="answer in subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].examAnswers"
                        size="large" :value="answer.answerId">
                        {{ answer.answerContent }}</el-radio>
                </el-radio-group>
            </el-form>
            <!-- 填空题 -->
            <!-- <el-form v-else-if="subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].questionType == 's'">
                <div class="subject-type"><span>填空题</span></div>
                <div class="subject">
                    <span>{{ subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].questionContent }}</span>
                </div>
                <el-input v-model="answerBinds" :rows="4" type="textarea" placeholder="请输入答案" />
            </el-form> -->
            <!-- 代码编辑器 -->
            <div v-else-if="subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].questionType == 'c' && subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].examQuestionCode.baseCode"
                class="codeEditor">
                <div class="subDescription">
                    <div class="title">
                        <h3>{{ subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].examQuestionCode.title }}
                        </h3>
                    </div>
                    <div class="description">
                        <span>{{ subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].examQuestionCode.describe
                        }}</span>
                    </div>
                    <div class="tips">
                        <strong>你可以在你自己的代码编辑器中攥写并且调试代码,<br>在调试好后再把代码粘贴到下面的代码编辑器中作为答案。</strong>
                    </div>
                    <div class="example">
                        <strong>示例: </strong>
                        <p><strong>输入:输出： </strong> {{ input.inputData }} </p>
                    </div>
                    <div class="judge">
                        <strong>评判代码: </strong>
                        <p>1. 代码正确性: 代码能够正确通过测试用例。</p>
                        <p>2. 确保代码与下列声明的函数一致。</p>
                        <Codemirror v-model:value="judgeCode" :options="judgeCmOptions" border ref="cmRef" height="260px"
                            width="500px" @change="" @input="" @ready="">
                        </Codemirror>
                    </div>
                </div>
                <div class="codeEdit">
                    <el-select v-model="codeSelect" placeholder="C" style="width: 240px">
                        <el-option v-for="item in codeMode" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                    <Codemirror v-model:value="code" :options="cmOptions" border ref="cmRef" height="80%" width="100%"
                        @change="" @input="" @ready="">
                    </Codemirror>
                </div>
            </div>
        </div>
        <el-dialog v-model="dialogVisible" title="Tips" width="500">
            <el-alert title="一旦确认即为确认最终成绩,请三思!!!" type="error" />
            <el-alert title="一旦确认即为确认最终成绩,请三思!!!" type="error" />
            <el-alert title="一旦确认即为确认最终成绩,请三思!!!" type="error" />
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="clickComfirm">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>


<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router';
import { onMounted, reactive, ref, watch } from "vue";
import { useSubjects } from "../stores/subjectStore"
import { useAnswer, type Answer } from '../stores/answerStore';
import { useUrlStore } from '../stores/urlStore';
import message_notice from '../functional/message_notice';
import { ElMessageBox } from 'element-plus'
import "codemirror/mode/clike/clike"
import Codemirror from "codemirror-editor-vue3"
import type { CmComponentRef } from "codemirror-editor-vue3"
import type { Editor, EditorConfiguration } from "codemirror"


const subjectsStore = useSubjects()
const router = useRouter()
const urlStore = useUrlStore()
let questionType = ref('')
let code = ref('')          //用户编写的代码
let judgeCode = ref('')     //评判代码
let input = reactive({      //输入数据
    inputData: ""
})
let output = reactive({     //输出数据
    outputData: ""
})
let codeSelect = ref('')
const codeMode = reactive([
    { value: "c", label: "C" },
])
let answerData = reactive({
    answerContent: [] as Answer[]
})

// 用于双向绑定选择题答案内容
let answerBinds = ref(0)

onMounted(async () => {
    const route = useRoute()
    // 从myexam.vue传过来的examId
    let examId = route.params.examId
    let duration = route.params.duration
    // 获取当前考试的题目
    subjectsStore.getSubjects()

    setTimeout(() => {
        code.value = subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].examQuestionCode.baseCode
        judgeCode.value = subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].examQuestionCode.umpireCode
        if (subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].examAnswers[0]) {
            input.inputData = subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].examAnswers[0].answerContent
        }
    }, 200)
})

const checkDuplicate = (getAnswer: Answer) => {
    const existAnswer = answerData.answerContent.find(item => item.questionId === getAnswer.questionId)
    if (existAnswer) {
        answerData.answerContent.splice(answerData.answerContent.indexOf(existAnswer), 1)
    }
}

//上一题
const upperStage = () => {
    if (subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].questionType !== 'c') {
        // 当点击下一题的时候保存当前的答案
        let questionId = subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].questionId
        let respond = answerBinds.value.toString()
        // 在插入数据前检查是否存在相同的数据 存在就顶掉
        checkDuplicate({ questionId: questionId, respond: respond })
        answerData.answerContent.push({ questionId: questionId, respond: respond })
        if (subjectsStore.curSubjectIndex > 0) {
            subjectsStore.curSubjectIndex -= 1
        }
        if (subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].questionType !== 'c') {
            questionId = subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].questionId
            let existAnswer = answerData.answerContent.find(item => item.questionId === questionId)
            if (existAnswer) {
                if (existAnswer.respond !== undefined) {
                    answerBinds.value = parseInt(existAnswer.respond)
                }
            }
        } else {
            code.value = subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].examQuestionCode.baseCode
            judgeCode.value = subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].examQuestionCode.umpireCode
            questionId = subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].questionId
            if (subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].examAnswers[0]) {
                input.inputData = subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].examAnswers[0].answerContent
            }
            let existAnswer = answerData.answerContent.find(item => item.questionId === questionId)
            if (existAnswer) {
                if (existAnswer.respondDesc !== undefined) {
                    code.value = existAnswer.respondDesc
                }
            }
        }
    } else {
        let questionId = subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].questionId
        let respond = code.value

        // 在插入数据前检查是否存在相同的数据 存在就顶掉
        checkDuplicate({ questionId: questionId, respond: respond })
        answerData.answerContent.push({ questionId: questionId, respondDesc: respond })
        if (subjectsStore.curSubjectIndex < subjectsStore.subjetcLength - 1) {
            subjectsStore.curSubjectIndex -= 1
        }
        code.value = subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].examQuestionCode.baseCode
        judgeCode.value = subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].examQuestionCode.umpireCode
        questionId = subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].questionId
        input.inputData = ""
        if (subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].examAnswers[0]) {
            input.inputData = subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].examAnswers[0].answerContent
        }
        let existAnswer = answerData.answerContent.find(item => item.questionId === questionId)
        if (existAnswer) {
            if (existAnswer.respondDesc !== undefined) {
                code.value = existAnswer.respondDesc
            }
        }
    }
}

// 下一题
const netxStage = () => {
    // 判断当前题目是否为code题 不是就保存在
    if (subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].questionType !== 'c') {
        // 当点击下一题的时候保存当前的答案
        let questionId = subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].questionId
        let respond = answerBinds.value.toString()
        // 在插入数据前检查是否存在相同的数据 存在就顶掉
        checkDuplicate({ questionId: questionId, respond: respond })
        answerData.answerContent.push({ questionId: questionId, respond: respond })
        if (subjectsStore.curSubjectIndex > 0) {
            subjectsStore.curSubjectIndex += 1
        }
        questionId = subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].questionId
        let existAnswer = answerData.answerContent.find(item => item.questionId === questionId)
        if (existAnswer) {
            if (existAnswer.respond !== undefined) {
                answerBinds.value = parseInt(existAnswer.respond)
            }
        } else {
            answerBinds.value = 0
        }
    } else {
        let questionId = subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].questionId
        let respond = code.value
        // 在插入数据前检查是否存在相同的数据 存在就顶掉
        checkDuplicate({ questionId: questionId, respond: respond })
        answerData.answerContent.push({ questionId: questionId, respondDesc: respond })
        if (subjectsStore.curSubjectIndex < subjectsStore.subjetcLength - 1) {
            subjectsStore.curSubjectIndex += 1
        }
        code.value = subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].examQuestionCode.baseCode
        judgeCode.value = subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].examQuestionCode.umpireCode
        questionId = subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].questionId
        if (subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].examAnswers[0]) {
            input.inputData = subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].examAnswers[0].answerContent
        }
        let existAnswer = answerData.answerContent.find(item => item.questionId === questionId)
        if (existAnswer) {
            if (existAnswer.respondDesc !== undefined) {
                code.value = existAnswer.respondDesc
            }
        }
    }
}

const postAnswer = async () => {
    // 发送答案到后端
    try {
        let token: any = sessionStorage.getItem('token')
        let resp = await fetch(`${urlStore.baseurl}/exam/updateResponds`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'token': token
            },
            body: JSON.stringify(answerData.answerContent)
        })
        let data = await resp.json()
        message_notice("提交答案成功", "success")
    } catch (error) {
        message_notice("提交答案失败", "error")
    }
}

const submitAnswer = () => {
    // 在提交答案之前获取最后一题的答案
    let lastAnswerId = subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].questionId
    let lastRespond = answerBinds.value.toString()
    // 在插入数据前检查是否存在相同的数据 存在就顶掉
    checkDuplicate({ questionId: lastAnswerId, respond: lastRespond })
    if (subjectsStore.subjects.subjectData[subjectsStore.curSubjectIndex].questionType !== 'c') {
        answerData.answerContent.push({ questionId: lastAnswerId, respond: lastRespond })
    } else {
        answerData.answerContent.push({ questionId: lastAnswerId, respondDesc: code.value })
    }
    postAnswer()
}

// 代码编辑器
const cmOptions: EditorConfiguration = {
    mode: "text/x-c++src"
}
const judgeCmOptions: EditorConfiguration = {
    mode: "text/x-c++src",
    readOnly: true
}

//最终确定答案
const postComfirmAnswer = async () => {
    // 发送确认答案到后端
    try {
        let token: any = sessionStorage.getItem('token')
        let resp = await fetch(`${urlStore.baseurl}/exam/finishExam`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'token': token
            }
        })
        let data = await resp.json()
        message_notice("交卷成功", "success")
    } catch (error) {
        message_notice("交卷失败", "error")
    }
}

let dialogVisible = ref(false)

const clickComfirm = () => {
    ElMessageBox.confirm("真的确定要提交答案吗? 交卷后将无法再修改答案!!!",
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        .then(() => {
            submitAnswer()
            setTimeout(() => {
                postComfirmAnswer()
            }, 1000);
            dialogVisible.value = false
            router.push('/index')
        })
        .catch(() => {
            // catch error
        })
}

</script>


<style scoped lang="scss">
.answer-sheet {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;

    .top {
        width: 80%;
        height: 60px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        flex-direction: row;
    }

    .content {
        width: 95%;
        min-height: 500px;

        .subject-type {
            font-size: 28px;
            font-weight: bold;
            margin-bottom: 20px;
        }

        .subject {
            font-size: 30px;
            margin-bottom: 20px;

            span {
                font-size: 24px;
                font-weight: 700;
            }
        }

        .el-radio-group {
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            justify-content: center;
            padding: 0;
            margin: 0;
            width: 100%;

            .el-radio>>>.el-radio__label {
                display: block;
                font-size: 60px;
                line-height: 2;
                margin: 20px 0;
            }
        }

        .codeEditor {
            display: flex;
            flex-direction: row;
            justify-content: start;
            align-items: center;

            .subDescription {
                height: 95vh;
                display: flex;
                flex-direction: column;
                width: 800px;
                justify-content: start;
                align-items: start;
                margin-left: 30px;

                .title {
                    margin-top: 30px;
                    margin-bottom: 10px;

                    h3 {
                        font-size: 30px;
                        font-weight: bold;
                        color: #333;
                    }
                }

                .description {
                    margin-bottom: 30px;
                    font-size: 18px;
                    color: #666;
                }

                .tips {
                    margin-bottom: 30px;
                    font-size: 18px;
                    color: #383838;

                    strong {
                        font-size: 16px;
                        color: #383838;
                    }
                }

                .example {

                    margin-bottom: 30px;
                    font-size: 18px;
                    color: #383838;

                    p {
                        margin-top: 10px;
                    }
                }
            }

            .codeEdit {
                width: 680px;
                height: 95vh;
            }
        }
    }
}
</style>